package com.sainthigh.ip;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.http.conn.util.InetAddressUtils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class IPUtils {


	/**
	 * 01-02 03:24:10.960: W/System.err(2398): java.net.SocketException
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.rethrowAsSocketException(NetworkInterface.java:248)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:208)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getByNameInternal(NetworkInterface.java:127)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getNetworkInterfacesList(NetworkInterface.java:309)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.getNetworkInterfaces(NetworkInterface.java:298)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.sainthigh.ip.IPUtils.getLocalIpAddress(IPUtils.java:28)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.sainthigh.ip.IPActivity.onClick(IPActivity.java:28)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.view.View.performClick(View.java:4438)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.view.View$PerformClick.run(View.java:18422)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Handler.handleCallback(Handler.java:733)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Handler.dispatchMessage(Handler.java:95)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.os.Looper.loop(Looper.java:136)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at android.app.ActivityThread.main(ActivityThread.java:5001)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.lang.reflect.Method.invokeNative(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.lang.reflect.Method.invoke(Method.java:515)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at dalvik.system.NativeStart.main(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at libcore.io.Posix.socket(Native Method)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	at java.net.NetworkInterface.collectIpv4Address(NetworkInterface.java:193)
	 * <br>01-02 03:24:10.960: W/System.err(2398): 	... 16 more
	 * <br> 这种情况，添加  <uses-permission android:name="android.permission.INTERNET" />
	 * <br>获取本地ip
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			String ipv4 = null;
			List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
			for(NetworkInterface ni : nilist) {
				List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
				for (InetAddress address : ialist) {
					ipv4 = address.getHostAddress();
					if(!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4)) {
						return ipv4;
					}
				}
			}
		} catch(SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过本地ip获取mac地址
	 * @return
	 */
	public static String getLocalMacAddressFromIp() {
		String mac_s = "";
		try {
			byte[] mac;
			String ip = getLocalIpAddress();
			if(!InetAddressUtils.isIPv4Address(ip)) {
				return mac_s;
			}
			InetAddress ipAddress = InetAddress.getByName(ip);
			if(ipAddress == null) {
				return mac_s;
			}
			NetworkInterface ne = NetworkInterface.getByInetAddress(ipAddress);
			mac = ne.getHardwareAddress();
			if(mac.length > 0) {
				mac_s = byte2mac(mac);
			}
		} catch (Exception e){
			e.printStackTrace();
		} 
		return mac_s;
	}

	private static String byte2mac(byte[] b) {
		StringBuffer hs = new StringBuffer(b.length);
		String stmp = "";
		int len = b.length;
		for(int n=0; n<len; n++) {
			stmp = Integer.toHexString(b[n]&0xFF);
			if(stmp.length() == 1) {
				hs = hs.append("0").append(stmp);
			} else {
				hs = hs.append(stmp);
			}
		}
		StringBuilder str = new StringBuilder(hs);
		for (int i=0; i<str.length(); i++) {
			if(i%3==0) {
				str.insert(i, ":");
			}
		}
		return str.toString().substring(1);
	}

	/**
	 * 获取Ethernet的MAC地址
	 * @return
	 */
	public static String getMacAddress() {
		try{
			return loadFileAsString("/sys/class/net/eth0/address").toUpperCase(Locale.ENGLISH).substring(0, 17);
		}catch(IOException e){

		}
		return null;
	}

	/**
	 * 获取Ethernet的MAC地址
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	private static String loadFileAsString(String filePath) throws IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while((numRead=reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
		}
		reader.close();
		return fileData.toString();
	}

	/**
	 * 获取Ethernet的MAC地址，简单的方法
	 * @return
	 */
	//	public static String getMacAddress(Activity activity) {
	//		EthernetManager ethManager = activity.getSystemService("ethernet");
	//		return ethManger.getMacAddr()==null?"":ethManger.getMacAdr();
	//	}

	/**
	 * 获取wifi Mac
	 * @return
	 */
	private String getWifiMac(Context ctx) {
		WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress()==null?"":info.getMacAddress();
	}

}
